import {Handler} from "./Handler";
import * as interact from "interactjs";
import {MapCamera} from "../render/MapCamera";
import {MapRenderer} from "../render/MapRenderer";
import {Interactable} from "interactjs";

export class DragHandler extends Handler {
    protected camera: MapCamera;

    protected mapRenderer: MapRenderer;

    protected interactable: Interactable;

    disable(): void {
        if (this.interactable) {
            (this.interactable as any).options.drag.enabled = false;
        }
    }

    enable(): void {
        this.map.container.style.touchAction = 'none';
        this.interactable = interact(this.map.container).draggable({
            onmove: e => this.onPan(e),
            onend: e => this.onPanEnd(e),
            onstart: e => this.onPanStart(e)
        });
    }

    init(): void {
        this.mapRenderer = this.map.mapRenderer;
        this.camera = this.mapRenderer.camera;
    }

    private onPan(e: interact.InteractEvent) {
        let r = this.camera.getResolution();
        this.mapRenderer.camera.moveBy(-e.dx * r,e.dy * r)
    }

    onPanEnd(e: interact.InteractEvent) {
        this.map.eventDispatcher.dispatchEvent({
            event: e,
            type: "panend"
        });
    }

    onPanStart(e: interact.InteractEvent) {
        this.map.eventDispatcher.dispatchEvent({
            event: e,
            type: "panstart"
        });
    }
}
